<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\learn\book;

use app\api\model\Order as OrderModel;
use app\api\service\User as UserService;
use app\common\library\helper;
use app\common\model\learn\book\Comment as CommentModel;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 商品评价模型
 * Class Comment
 * @package app\api\model
 */
class Comment extends CommentModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'user_id',

		'store_id',
		'is_delete',
		'update_time',
	];

	/**
	 * 获取指定商品评价列表
	 * @param int $goodsId 商品ID
	 * @param int|null $scoreType 评分 (10好评 20中评 30差评)
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getList(int $articleId, $params): \think\Paginator {
		$userId = UserService::getCurrentLoginUserId();

		$filter = $this->getFilter($articleId, $params);
		if ($params['current'] == 0) {

			$list = $this

				->where($filter)
				->order(['is_hot' => 'desc', 'like_views' => 'desc'])
				->paginate(15);

		}
		if ($params['current'] == 1) {
			// 最新排序
			$list = $this->where($filter)
				->order(['create_time' => 'desc'])
				->paginate(15);
		}
		if ($params['current'] == 2) {

			//收藏
			$log = Db::name('learn_book_comment_log')->where('article_id', $articleId)
				->where('user_id', $userId)->where('status', 2)->select()->toArray();
			if ($log) {

				$ids = array_column($log, 'comment_id');

				$list = $this->where($filter)

					->where('comment_id', 'in', $ids)
					->order(['create_time' => 'desc'])
					->paginate(15);

			} else {

				$list = $this
					->where('store_id', -1)

					->paginate(15);
			}

		}

		foreach ($list as &$item) {
			$is_collect = Db::name('learn_article_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 2)->find();
			$item['is_collect'] = $is_collect ? 1 : 0;
			$is_collect = Db::name('learn_article_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 1)->find();
			$item['is_step'] = $is_collect ? 1 : 0;
			$is_collect = Db::name('learn_article_comment_log')->where('user_id', $userId)->where('comment_id', $item['comment_id'])->where('status', 0)->find();
			$item['is_like'] = $is_collect ? 1 : 0;

		}

		// 加载商品评价的关联数据
		return static::preload($list, ['user.avatar']);
	}

	/**
	 * 获取指定商品评价列表 (限制数量, 不分页)
	 * @param int $goodsId 商品ID
	 * @param int $limit 限制的数量
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function listRows(int $goodsId, int $limit = 5): \think\Collection {
		$filter = $this->getFilter($goodsId);
		return $this->with(['user.avatar'])
			->where($filter)
			->order(['sort' => 'asc', $this->getPk()])
			->limit($limit)
			->select();
	}

	/**
	 * 获取指定商品评价总数量
	 * @param int $goodsId
	 * @return int
	 */
	public function rowsTotal(int $goodsId): int {
		$filter = $this->getFilter($goodsId);
		return $this->where($filter)->count();
	}

	/**
	 * 获取查询条件
	 * @param int $goodsId 商品ID
	 * @param int|null $scoreType 评分 (10好评 20中评 30差评)
	 * @return array[]
	 */
	private function getFilter(int $articleId, $params): array {
		// 筛选条件
		$filter = [
			['article_id', '=', $articleId],
			['parent_id', '=', $params['pid']],
			['status', '=', 1],
			['is_delete', '=', 0],
		];
		if (!empty($params['keyword'])) {
			$filter[] = ['content', 'like', '%' . $params['keyword'] . '%'];
		}

		return $filter;
	}

	/**
	 * 获取指定评分总数
	 * @param int $goodsId
	 * @return array|null|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function getTotal(int $goodsId) {
		return $this->field([
			'count(comment_id) AS `all`',
			'count(score = 10 OR NULL) AS `praise`',
			'count(score = 20 OR NULL) AS `review`',
			'count(score = 30 OR NULL) AS `negative`',
		])->where([
			'goods_id' => $goodsId,
			'is_delete' => 0,
			'status' => 1,
		])->find();
	}

	/**
	 * 验证订单是否允许评价
	 * @param OrderModel $order
	 * @return boolean
	 */
	public function checkOrderAllowComment(OrderModel $order): bool {
		// 验证订单是否已完成
		if ($order['order_status'] != 30) {
			$this->error = '该订单未完成，无法评价';
			return false;
		}
		// 验证订单是否已评价
		if ($order['is_comment'] == 1) {
			$this->error = '该订单已完成评价';
			return false;
		}
		return true;
	}

	/**
	 * 添加评论
	 * @param OrderModel $order
	 * @param $goodsList
	 * @param array $data
	 * @return boolean
	 * @throws BaseException
	 */
	public function increased(array $data): bool {

		$data['user_id'] = UserService::getCurrentLoginUserId();
		$data['store_id'] = self::$storeId;
		$this->save($data);

		if ($data['parent_id'] > 0) {
			Db::name('learn_book_comment')->where('comment_id', $data['parent_id'])
				->inc('comment_views', 1)->update();
		}

		return true;

	}
	/*
		*收藏
	*/
	public function collectSave($data): bool {
		$userId = UserService::getCurrentLoginUserId();
		if ($data['is_collect'] == 0) {
			Db::name('learn_book_comment_log')
				->where('status', $data['status'])->where('user_id', $userId)->where('comment_id', $data['comment_id'])->delete();

			if ($data['status'] == 2) {
				$this->where('comment_id', $data['comment_id'])->dec('collect_views', 1)->update();
			} elseif ($data['status'] == 1) {
				$this->where('comment_id', $data['comment_id'])->dec('step_views', 1)->update();
			} else {
				$this->where('comment_id', $data['comment_id'])->dec('like_views', 1)->update();
			}

			return true;

		}
		$data['article_id'] = $data['article_id'];
		$data['comment_id'] = $data['comment_id'];

		$data['user_id'] = $userId;
		$data['create_time'] = time();
		$data['store_id'] = self::$storeId;
		unset($data['is_collect']);
		Db::name('learn_book_comment_log')->insert($data);

		if ($data['status'] == 2) {
			$this->where('comment_id', $data['comment_id'])->inc('collect_views', 1)->update();
		} elseif ($data['status'] == 1) {
			$this->where('comment_id', $data['comment_id'])->inc('step_views', 1)->update();
		} else {
			$this->where('comment_id', $data['comment_id'])->inc('like_views', 1)->update();
		}

		return true;

	}

	/**
	 * 更新订单评价状态
	 * @param OrderModel $order
	 * @param $isComment
	 * @param $commentList
	 * @return void
	 */
	private function updateOrderIsComment(OrderModel $order, $isComment, $commentList): void {
		// 更新订单商品
		$orderGoodsData = [];
		foreach ($commentList as $comment) {
			$orderGoodsData[] = [
				'where' => [
					'order_goods_id' => $comment['order_goods_id'],
				],
				'data' => [
					'is_comment' => 1,
				],
			];
		}
		// 更新订单
		$isComment && $order->save(['is_comment' => 1]);
		(new OrderGoods)->updateAll($orderGoodsData);
	}

	/**
	 * 生成评价数据
	 * @param int $orderId
	 * @param $goodsList
	 * @param array $formData
	 * @return array
	 * @throws BaseException
	 */
	private function createCommentData(int $orderId, $goodsList, array $formData): array {
		$data = [];
		foreach ($goodsList as $goods) {
			if (!isset($formData[$goods['order_goods_id']])) {
				throwError('提交的数据不合法');
			}
			$commentItem = $formData[$goods['order_goods_id']];
			$commentItem['content'] = trim($commentItem['content']);
			!empty($commentItem['content']) && $data[$goods['order_goods_id']] = [
				'score' => $commentItem['score'],
				'content' => $commentItem['content'],
				'is_picture' => !empty($commentItem['uploaded']),
				'sort' => 100,
				'status' => 1,
				'user_id' => UserService::getCurrentLoginUserId(),
				'order_id' => $orderId,
				'goods_id' => $commentItem['goods_id'],
				'order_goods_id' => $commentItem['order_goods_id'],
				'store_id' => self::$storeId,
			];
		}
		return $data;
	}

	/**
	 * 格式化 formData
	 * @param array $data
	 * @return array
	 */
	private function formatFormData(array $data): array {
		return helper::arrayColumn2Key($data, 'order_goods_id');
	}

}
